<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <todo-header :list="list" @add-todo="addTodo"></todo-header>
    <todo-main :list="newList" @del-todo="delTodo"></todo-main>
    <todo-footer
      :list="list"
      :state="state"
      @change-state="changeState"
      @clear-finished="clearFinished"
    ></todo-footer>
  </section>
</template>

<script>
import TodoHeader from "./views/head.vue"
import TodoMain from "./views/list.vue"
import TodoFooter from "./views/foot.vue"

import "./style/base.css"
import "./style/index.css"
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  computed: {
    newList () {
      if (this.state === 'all') {
        return this.list
      } else if (this.state === 'unfinish') {
        return this.list.filter(item => !item.isDone)
      } else {
        return this.list.filter(item => item.isDone)
      }
    }
  },
  data () {
    return {
      list: JSON.parse(localStorage.getItem('todolist')),
      state: 'all'
    }
  },
  watch: {
    list: {
      handler (newVal) {
        localStorage.setItem('todolist', JSON.stringify(newVal))
      },
      deep: true
    }
  },
  methods: {
    addTodo (todoName) {
      this.list.unshift(
        {
          id: Date.now(),
          name: todoName,
          isDone: false
        }
      )
    },
    delTodo (id) {
      this.list = this.list.filter(item => item.id !== id)
    },
    changeState (state) {
      this.state = state
    },
    clearFinished () {
      this.list = this.list.filter(item => !item.isDone)
    }
  },
};
</script>